from threading import Thread
import os, sys
try:
    from win32api import GetSystemMetrics
    import numpy as np
    import cv2
except:
    os.system("pip3 install --user pypiwin32 numpy opencv-python")
    from win32api import GetSystemMetrics
    import numpy as np
    import cv2


def gbk_to_utf8(a1):
    s1 = ''
    s2 = ['\u200b', '\ufffd', '\u2764', '\u2795', '\u270a', '\u202c', '\ue312', '\u2b50', '\u200e', '\u1ea3', '\u2006']
    #for i in a1:

        

def thread_match():
    thread_match.v5 = 0.7
    retu = cv2.matchTemplate(main.img, main.crop, cv2.TM_CCOEFF_NORMED)
    thread_match.index = np.where(retu > thread_match.v5)
    max_index = []
    v3 = np.unique(np.concatenate(( np.asarray([0], dtype=int), np.asarray([len(thread_match.index[0])-1], dtype=int), np.where(abs(np.diff(np.sort(thread_match.index[0]))) > 2)[0]+1, np.where(abs(np.diff(np.sort(thread_match.index[1]))) > 3)[0]+1 ), axis=0))   #分割
    #print(v3, thread_match.index)
    if len(v3)>=1:
        for i in range(len(v3)-1):
            v4 = np.argmax(retu[thread_match.index[0][v3[i]:v3[i+1]], thread_match.index[1][v3[i]:v3[i+1]]])
            v1 = thread_match.index[0][v4 +v3[i]]
            v2 = thread_match.index[1][v4 +v3[i]]
            v6 = retu[v1, v2]
            color = (int(main.color[0]*v6), int(main.color[1]*v6), int((main.color[2]+255)*v6))
            # (Blue, Green, Red): It will complex which are without "255-".
            v7 = str("{:.1%}".format(retu[v1, v2])[:-3])
            if v7 == "100":
                cv2.rectangle(main.img_show, (v2, v1), (v2+main.crop_w, v1+main.crop_h), color, 6)
            else:
                cv2.rectangle(main.img_show, (v2, v1), (v2+main.crop_w, v1+main.crop_h), color, 4)
                cv2.putText(main.img_show, v7, (v2, v1-10), cv2.FONT_HERSHEY_TRIPLEX, 1, color, 2)
            #cv2.imshow("%s Found" %len(thread_match.index[0]), main.img_show)
        

def def_crop():
    main.q1_x_min = min(main.q1_x)
    main.q1_x_max = max(main.q1_x)
    main.q2_y_min = min(main.q2_y)
    main.q2_y_max = max(main.q2_y)
    if min(main.q2_y) < 0: main.v_crop_1 = 0
    else: main.v_crop_1 = min(main.q2_y)
    if max(main.q2_y) > main.v_h: main.v_crop_2 = main.v_h
    else: main.v_crop_2 = max(main.q2_y)
    if min(main.q1_x) < 0: main.v_crop_3 = 0
    else: main.v_crop_3 = min(main.q1_x)
    if max(main.q1_x) > main.v_w: main.v_crop_4 = main.v_w
    else: main.v_crop_4 = max(main.q1_x)
    main.crop = main.img[main.v_crop_1:main.v_crop_2, main.v_crop_3:main.v_crop_4]
    main.crop_w = main.v_crop_4 - main.v_crop_3
    main.crop_h = main.v_crop_2 - main.v_crop_1
    

def main_ui(event, x, y, flags, param):

    if event == cv2.EVENT_LBUTTONDOWN:
        main.is_LBUTTONDOWN = True
        if main.is_RBUTTONDOWN == True:
            main.is_skip_LBUTTONDOWN = True
        if main.is_RBUTTONDOWN == False and main.is_skip_LBUTTONDOWN == False:
            main.q1_x.append(x)
            main.q2_y.append(y)
            main.img_show = main.img.copy()
            cv2.rectangle(main.img_show, (min(main.q1_x), min(main.q2_y)), (max(main.q1_x), max(main.q2_y)), main.color, 1)
    
    if event == cv2.EVENT_MOUSEMOVE and main.is_LBUTTONDOWN == True:
        main.img_show = main.img.copy()
        cv2.rectangle(main.img_show, (min(main.q1_x+[x]), min(main.q2_y+[y])), (max(main.q1_x+[x]), max(main.q2_y+[y])), main.color, 1)

    if event == cv2.EVENT_LBUTTONUP:
        main.is_LBUTTONDOWN = False
        if main.is_skip_LBUTTONDOWN == False:
            main.q1_x.append(x)
            main.q2_y.append(y)
            main.img_show = main.img.copy()
            def_crop()
            cv2.rectangle(main.img_show, (main.q1_x_min, main.q2_y_min), (main.q1_x_max, main.q2_y_max), main.color, 10)
            t=Thread(target=thread_match)
            t.start()
        if main.is_skip_LBUTTONDOWN:
            main.is_skip_LBUTTONDOWN = False

    if event == cv2.EVENT_RBUTTONDOWN:
        main.is_RBUTTONDOWN = True
        if len(main.q1_x) == 0: sys.exit(0)
        def_crop()
        main.img_show = main.crop

    if event == cv2.EVENT_RBUTTONUP:
        main.is_RBUTTONDOWN = False
        if main.is_LBUTTONDOWN == False:
            #d_save()
            main.is_destroyAllWindows = True
        if main.is_LBUTTONDOWN == True:
            main.img_show = main.img
            main.q1_x = []
            main.q2_y = []


def main(a1):
    main.a1 = a1
    main.q1_x = []
    main.q2_y = []
    s1_window = int(GetSystemMetrics(0)*5/6)
    s2_window = int(GetSystemMetrics(1)*5/6)
    main.color = (0, 0, 0)
    main.is_LBUTTONDOWN = False
    main.is_RBUTTONDOWN = False
    main.is_skip_LBUTTONDOWN = False
    main.title = os.path.basename(a1).encode("gbk").decode(errors="ignore")
    main.img = cv2.imdecode(np.fromfile(main.a1, dtype=np.uint8), -1)
    try:
        cv2.matchTemplate(main.img, main.img, cv2.TM_CCOEFF_NORMED)
    except:
        main.img = cv2.imread(main.a1, 0)

    try:
        main.v_h, main.v_w, _ = main.img.shape
    except:
        main.v_h, main.v_w = main.img.shape

    cv2.namedWindow(main.title, 0)
    main.img_show = main.img.copy()
    main.is_destroyAllWindows = False
    cv2.setMouseCallback(main.title, main_ui)
    cv2.resizeWindow(main.title, s1_window, s2_window)

    while True:
        cv2.imshow(main.title, main.img_show)
        key = cv2.waitKey(1) & 0xFF
        if main.is_destroyAllWindows == True:
            # cv2.destroyAllWindows()
            break


if __name__ == "__main__":
    if len(sys.argv) >=2:
        for i in sys.argv[1:]:
            main(i)
    else:
        v = input(':').strip('\'\"\\').rstrip("/")
        main(v)
        sys.exit(0)